package com.jy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jy.common.enums.ResponseWrapper;
import com.jy.entity.SearchHistory;
import com.jy.entity.User;
import com.jy.mapper.SearchHistoryMapper;
import com.jy.mapper.UserMapper;
import com.jy.service.SearchHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 搜索历史表 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2024-11-12
 */
@Service
public class SearchHistoryServiceImpl extends ServiceImpl<SearchHistoryMapper, SearchHistory> implements SearchHistoryService {

    private final SearchHistoryMapper searchHistoryMapper;
    private final UserMapper userMapper;

    public SearchHistoryServiceImpl(SearchHistoryMapper searchHistoryMapper, UserMapper userMapper) {
        this.searchHistoryMapper = searchHistoryMapper;
        this.userMapper = userMapper;
    }

    @Override
    public ResponseWrapper getHotSearchKey() {
        // 查询所有搜索关键词记录
        List<SearchHistory> allKeywords = searchHistoryMapper.selectList(null);

        // 使用HashMap来存储每个关键词及其出现的总次数
        Map<String, Integer> keywordCountMap = getStringIntegerMap(allKeywords);

        // 找出出现次数最多的关键词及其次数
        String mostSearchedKeyword = null;
        Integer maxCount = 0;
        for (Map.Entry<String, Integer> entry : keywordCountMap.entrySet()) {
            if (entry.getValue() > maxCount) {
                mostSearchedKeyword = entry.getKey();
                maxCount = entry.getValue();
            }
        }
        return ResponseWrapper.markSuccess(mostSearchedKeyword);
    }

    private static Map<String, Integer> getStringIntegerMap(List<SearchHistory> allKeywords) {
        Map<String, Integer> keywordCountMap = new HashMap<>();

        // 遍历所有记录，统计每个关键词的总次数
        for (SearchHistory keyword : allKeywords) {
            String keywordName = keyword.getName();
            Integer count = keyword.getCount();

            if (keywordCountMap.containsKey(keywordName)) {
                // 如果关键词已经在map中，累加次数
                keywordCountMap.put(keywordName, keywordCountMap.get(keywordName) + count);
            } else {
                // 如果关键词不在map中，添加新的键值对
                keywordCountMap.put(keywordName, count);
            }
        }
        return keywordCountMap;
    }

    @Override
    public ResponseWrapper deleteHistorySearchKeys(Integer userAid) {
        User user = userMapper.selectById(userAid);
        int delete = searchHistoryMapper.delete(new LambdaQueryWrapper<SearchHistory>()
                .eq(SearchHistory::getUserAid, userAid)
        );
        if (delete > 0) {
            return ResponseWrapper.markCustomSuccess("删除成功");
        }else {
            return ResponseWrapper.markCustomError("删除失败");
        }
    }

    @Override
    public ResponseWrapper addSearchHistory(Integer userAid, String keyValue) {

        // 返回结果
        HashMap<String, Object> map = new HashMap<>();

        SearchHistory searchHistory = searchHistoryMapper.selectOne(new LambdaQueryWrapper<SearchHistory>()
                .eq(SearchHistory::getUserAid, userAid)
                .eq(SearchHistory::getName, keyValue)
        );

        System.out.println("keyValue:  " + keyValue);
        if (searchHistory == null) {
            SearchHistory searchHistory1 = new SearchHistory();
            searchHistory1.setName(keyValue);
            searchHistory1.setUserAid((long)userAid);
            searchHistory1.setCount(1);
            searchHistory1.setHaveLabel(false);
            searchHistory1.setLabelName(null);
            searchHistoryMapper.insert(searchHistory1);
        }else {
            searchHistory.setCount(searchHistory.getCount() + 1);
            searchHistoryMapper.updateById(searchHistory);
        }

        // 根据搜索词查询用户
//        new ArrayList<HashMap>()

        // 查询全部，查询用户和笔记和商品（三样分开查，全部=笔记+用户+商品）

        return ResponseWrapper.markSuccess();
    }
}
